/**
 * Copyright (c) 2011-2017, dafei 李飞 (myaniu AT gmail DOT com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.epoch.base.shiro;

import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.UnauthenticatedException;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;

public class ShiroInterceptor implements Interceptor {

	public void intercept(Invocation ai) {
		AuthzHandler ah = ShiroKit.getAuthzHandler(ai.getActionKey());
		if (ah != null) {
			Controller  c = ai.getController();
			try {
				ah.assertAuthorized();
			}catch (UnauthenticatedException lae) {
				if(StrKit.notBlank(ShiroKit.getLoginUrl())){
					if(c.getRequest().getMethod().equalsIgnoreCase("GET")){
						c.setSessionAttr(ShiroKit.getSavedRequestKey(), ai.getActionKey());
					}
					c.redirect(ShiroKit.getLoginUrl());
				}else{
					c.renderError(401);
				}
				return;
			} catch (AuthorizationException ae) {
				if(StrKit.notBlank(ShiroKit.getUnauthorizedUrl())){
					c.redirect(ShiroKit.getUnauthorizedUrl());
				}else{
					c.renderError(403);
				}
				return;
			}
		}
		// 执行正常逻辑
		ai.invoke();
	}
}
